import os
import sys
from pathlib import Path
import xlrd  # 用于读取 Excel

# 当前脚本所在目录
script_dir = Path(__file__).parent

# Excel 文件路径和 sheet 名
excel_path = script_dir / "影片库.xlsx"
sheet_name = "演员库"

# 检查文件是否存在
if not excel_path.exists():
    print(f"❌ 错误：未找到 Excel 文件 '{excel_path}'")
    input("按回车键退出...")
    sys.exit(1)

# 尝试打开 Excel 文件
try:
    workbook = xlrd.open_workbook(excel_path)
except Exception as e:
    print(f"❌ 无法打开 Excel 文件：{e}")
    input("按回车键退出...")
    sys.exit(1)

# 检查 sheet 是否存在
if sheet_name not in workbook.sheet_names():
    print(f"❌ 找不到名为 '{sheet_name}' 的工作表。当前可用的 sheet：{workbook.sheet_names()}")
    input("按回车键退出...")
    sys.exit(1)

sheet = workbook.sheet_by_name(sheet_name)

# 查找表头行（第0行）
header = [str(cell.value).strip() for cell in sheet.row(0)]

# 定义所需字段及其在表头中的位置
required_fields = {
    "演员ID": None,
    "名字": None,
    "别名": None,
    "链接": None,
    "图片": None,
    "风格": None,
    "气质": None,
    "体型": None,
    "演技": None,
    "胸": None,
    "臀": None,
    "腿": None,
}

# 映射列索引
missing_cols = []
for field in required_fields.keys():
    try:
        required_fields[field] = header.index(field)
    except ValueError:
        missing_cols.append(field)

if missing_cols:
    print(f"❌ Excel 表头缺少以下字段：{', '.join(missing_cols)}")
    print(f"当前表头为：{header}")
    input("按回车键退出...")
    sys.exit(1)

# 创建输出目录
output_dir = script_dir / "actors"
output_dir.mkdir(exist_ok=True)

# 遍历数据行（从第1行开始）
success_count = 0
skip_count = 0

for row_idx in range(1, sheet.nrows):
    row = sheet.row(row_idx)

    def get_cell(col_name):
        col_idx = required_fields[col_name]
        cell = row[col_idx]
        value = str(cell.value).strip()
        # 如果是浮点数格式的整数（如 101.0），转成整数再转字符串
        if value.endswith('.0'):
            try:
                return str(int(float(value)))
            except:
                pass
        return value

    name = get_cell("名字")
    if not name or name in ["", "null", "None"]:
        print(f"⚠️ 第 {row_idx + 1} 行跳过：缺少名字")
        skip_count += 1
        continue

    actor_id = get_cell("演员ID")
    aliases_str = get_cell("别名")
    link = get_cell("链接")
    image = get_cell("图片")
    style = get_cell("风格")
    feel = get_cell("气质")
    body = get_cell("体型")
    acting = get_cell("演技")
    chest = get_cell("胸")
    hips = get_cell("臀")
    leg = get_cell("腿")

    # 解析别名（支持用分号、逗号或换行分隔）
    if aliases_str:
        aliases = [a.strip() for a in aliases_str.replace("\n", ";").replace("，", ",").replace("；", ";").split(";") if a.strip()]
    else:
        aliases = []
    # 确保名字本身也在别名中
    if name not in aliases:
        aliases.insert(0, name)

    # 构建 YAML frontmatter
    yaml_lines = [
        "---",
        "tags:",
        "  - 演员",
        "  - 成人演员",
        "type: actor",
        f"actor_id: {actor_id}",
        f"name: {name}",
        "aliases:"
    ]
    for alias in aliases:
        yaml_lines.append(f"  - {alias}")

    yaml_lines.extend([
        f"style: {style}",
        f"feel: {feel}",
        f"body: {body}",
        f"acting: {acting}",
        f"chest: {chest}",
        f"hips: {hips}",
        f"leg: {leg}",
        "---"
    ])

    # 正文内容
    content_lines = [
        "",
        "# 头像",
        "",
        image,
        "",
        "# 照片",
        "",
        "",
        "# 影片库",
        "",
        "```dataview",
        'LIST ',
        f'WHERE type = "movie" AND contains(actors, "{name}")',
        "```"
    ]

    # 合并内容
    file_content = "\n".join(yaml_lines + content_lines)

    # 文件名处理（避免重复）
    filename = f"{name}.md"
    file_path = output_dir / filename
    counter = 1
    original_filename = filename
    while file_path.exists():
        filename = f"{name}_{counter}.md"
        file_path = output_dir / filename
        counter += 1

    # 写入文件
    try:
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(file_content)
        print(f"✅ 已生成: {filename}")
        success_count += 1
    except Exception as e:
        print(f"❌ 写入文件 {filename} 失败：{e}")

# 最终统计
print(f"\n🎉 完成！")
print(f"✔️ 成功生成 {success_count} 个文件")
if skip_count > 0:
    print(f"⚠️ 跳过 {skip_count} 条缺失名字的数据")
print(f"📁 输出目录：{output_dir}")

# 防止窗口一闪而过（适合双击运行）
input("\n按回车键关闭...")